package com.aida.evil.eda;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.ViewDragHelper;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.SparseArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.aida.evil.aida.R;
import com.aida.evil.eda.Answer.ImageZoom;
import com.aida.evil.eda.Data.Fragment_Data;
import com.aida.evil.eda.Data.NetworkData;
import com.aida.evil.eda.Data.UserData;
import com.aida.evil.eda.Toast.CustomSuperActivityToast;
import com.aida.evil.eda.Toast.CustomSuperCardToast;
import com.aida.evil.eda.Volley.VolleyHandler;
import com.aida.evil.eda.Volley.VolleyHttpRequest;
import com.aida.evil.eda.Window.CustomDialog;
import com.aida.evil.eda.Window.MainActivity_ExitDialog;
import com.aida.evil.eda.fragment.ContentFragment;
import com.github.johnpersano.supertoasts.SuperCardToast;
import com.github.johnpersano.supertoasts.SuperToast;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import io.codetail.animation.SupportAnimator;
import io.codetail.animation.ViewAnimationUtils;
import yalantis.com.sidemenu.interfaces.Resourceble;
import yalantis.com.sidemenu.interfaces.ScreenShotable;
import yalantis.com.sidemenu.model.SlideMenuItem;
import yalantis.com.sidemenu.util.ViewAnimator;

public class MainActivity extends AppCompatActivity implements ViewAnimator.ViewAnimatorListener
{
    private static final String MESSAGEURL = "http://" + NetworkData.ServiceIP + "/SendMessage?";

    private static String MARK_左侧栏已选中项 = "首页";//保存当前的Fragment的名称，防止再次点击

    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle drawerToggle;
    private List<SlideMenuItem> list = new ArrayList<>();

    private ViewAnimator viewAnimator;
    private LinearLayout linearLayout;

    private Toolbar toolbar;//顶部栏目

    //private Map<String, Integer> stringIntegerMap;//关联左侧菜单的名称与图片，存储关联的map

    private SparseArray<String> map_图片id_项目名称;//关联左侧菜单的名称与图片，存储关联的map-->左部分是图片的id(Integer),右部分是项目名称(String)
    //SparseArray继承与Map，比Map效率更高
    //SparseArray<Object>  等同于Map<Integer,Object> Object可以放入任何对象


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /**
         * 获取信息
         */


        /**
         * stringIntegerMap_关联左侧菜单的名称与图片()
         */
        stringIntegerMap_关联左侧菜单的名称与图片();
        /**
         * 首次加载Fragment
         */

        Fragment_Data fragment_data = new Fragment_Data();
        fragment_data.Fragmentstart();

        ContentFragment contentFragment = ContentFragment.newInstance(R.mipmap.eda);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.content_frame, contentFragment)
                .commit();
        //contentFragment = ContentFragment.newFragment("首页");
        getSupportFragmentManager().beginTransaction().
                add(R.id.mainactivity_fragmentlinearlayout, Fragment_Data.eda_Fragment).
                commit();


        /**
         * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
         */
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawerLayout.setScrimColor(Color.TRANSPARENT);//TRANSPARENT透明

        /**
         * 作用不明确
         */
        linearLayout = (LinearLayout) findViewById(R.id.left_drawer);
        linearLayout.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                drawerLayout.closeDrawers();
            }
        });

        setActionBar();
        /**
         * 加载左侧列表及其图片
         */
        createMenuList();

        /**
         * 左部弹出菜单
         */
        viewAnimator = new ViewAnimator<>(this, list, contentFragment, drawerLayout, this);
        /**
         * 弹出消息框
         */
        sendMessage();

        /**
         * 二维码
         */
        qrImageView();
    }

    /**
     * 二维码
     */
    private void qrImageView()
    {
        ImageView imageView = (ImageView) findViewById(R.id.mainactivity_qrImageView);
        imageView.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent intent = new Intent(MainActivity.this, ImageZoom.class);
                intent.putExtra("IMGRES", R.mipmap.qr);
                startActivity(intent);
            }
        });
    }


    /**
     * public static final String list_关闭 = "关闭";
     * public static final String list_首页 = "首页";
     * public static final String list_成绩 = "成绩";
     * public static final String list_积分 = "积分";
     * public static final String list_商城 = "商城";
     * public static final String list_关于 = "关于";
     */
    private void stringIntegerMap_关联左侧菜单的名称与图片()
    {
        map_图片id_项目名称 = new SparseArray<>();
        map_图片id_项目名称.put(R.mipmap.icn_1, "首页");
        //map_图片id_项目名称.put(R.mipmap.icn_2, "成绩");
        map_图片id_项目名称.put(R.mipmap.icn_2, "我的");
        map_图片id_项目名称.put(R.mipmap.icn_3, "分享");
        map_图片id_项目名称.put(R.mipmap.icn_4, "关于");
    }

    /**
     * 加载左侧列表及其图片
     *
     * @stringIntegerMap.keyAt(0) 获取SparseArray数组内position位置的图片  int值  R.id.xxx
     */
    private void createMenuList()
    {
        SlideMenuItem[] slideMenuItems = new SlideMenuItem[map_图片id_项目名称.size() + 1];
        slideMenuItems[0] = new SlideMenuItem("关闭", R.mipmap.icn_close);
        list.add(slideMenuItems[0]);
        for (int i = 0; i < map_图片id_项目名称.size(); i++)
        {
            slideMenuItems[i] = new SlideMenuItem(map_图片id_项目名称.valueAt(i), map_图片id_项目名称.keyAt(i));
            list.add(slideMenuItems[i]);
        }

    }

    /**
     * 顶部菜单栏
     *
     * @drawerToggle 应该是右侧的菜单栏
     */
    private void setActionBar()
    {
        toolbar = (Toolbar) findViewById(R.id.toolbar);

        toolbar.setTitle(map_图片id_项目名称.valueAt(0));
        //toolbar.setLogo(map_图片id_项目名称.keyAt(0));

        setSupportActionBar(toolbar);//作用不明确
        getSupportActionBar().setHomeButtonEnabled(true);//作用不明确
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close)
        {

            @Override
            public void onDrawerClosed(View drawerView)
            {
                super.onDrawerClosed(drawerView);
                linearLayout.removeAllViews();
                linearLayout.invalidate();
            }

            @Override
            public void onDrawerSlide(View drawerView, float slideOffset)
            {
                super.onDrawerSlide(drawerView, slideOffset);
                if (slideOffset > 0.6 && linearLayout.getChildCount() == 0)
                {
                    viewAnimator.showMenuContent();//左侧栏显示
                }
            }

            @Override
            public void onDrawerOpened(View drawerView)
            {
                super.onDrawerOpened(drawerView);
            }
        };
        drawerLayout.addDrawerListener(drawerToggle);

        /*设置右划占屏幕比例*/
        try
        {
            setDrawerLeftEdgeSize(this, drawerLayout, 0.2f);
        }
        catch (IllegalAccessException e)
        {
        }
        catch (NoSuchFieldException e)
        {
        }
    }

    /**
     * 设置右划占屏幕比例
     *
     * @param activity               活动界面
     * @param drawerLayout           传入drawerLayout
     * @param displayWidthPercentage 屏占比例 格式：0.3f
     * @throws IllegalAccessException
     * @throws NoSuchFieldException
     */
    public static void setDrawerLeftEdgeSize
    (Activity activity,
     DrawerLayout drawerLayout,
     float displayWidthPercentage)
            throws IllegalAccessException, NoSuchFieldException
    {
        if (activity == null || drawerLayout == null)
        {
            return;
        }
        {// find ViewDragHelper and set it accessible
            Field leftDraggerField = drawerLayout.getClass().getDeclaredField(
                    "mLeftDragger");
            leftDraggerField.setAccessible(true);
            ViewDragHelper leftDragger = (ViewDragHelper) leftDraggerField
                    .get(drawerLayout);
            // find edgesize and set is accessible
            Field edgeSizeField = leftDragger.getClass().getDeclaredField(
                    "mEdgeSize");
            edgeSizeField.setAccessible(true);
            int edgeSize = edgeSizeField.getInt(leftDragger);
            // set new edgesize
            // Point displaySize = new Point();
            DisplayMetrics dm = new DisplayMetrics();
            activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
            edgeSizeField.setInt(leftDragger, Math.max(edgeSize,
                    (int) (dm.widthPixels * displayWidthPercentage)));
        }
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState)
    {
        super.onPostCreate(savedInstanceState);
        drawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
        drawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    /**
     * 右侧下拉菜单
     */
    /*@Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        if (drawerToggle.onOptionsItemSelected(item))
        {
            return true;
        }
        switch (item.getItemId())
        {
            case R.id.action_settings:
            {
                Log.i("点击", "点击");
            }
            return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
*/

    /**
     * 左侧栏部分
     *
     * @param slideMenuItem  左侧的栏目,单个项目按钮
     * @param screenShotable 应该是退回到主界面
     * @param position       选中某个栏目按钮的位置指针
     * @return
     */

    @Override
    public ScreenShotable onSwitch(Resourceble slideMenuItem, ScreenShotable screenShotable, int position)
    {
        switch (slideMenuItem.getName())
        {

            case "关闭":
                return screenShotable;
            default:
            {
                String name = slideMenuItem.getName();
                if (MARK_左侧栏已选中项 != name)
                {
                    MARK_左侧栏已选中项 = name;
                    toolbar.setTitle(name);//设置toolbar的标题
                    toolbar.setLogo(map_图片id_项目名称.keyAt(map_图片id_项目名称.indexOfValue(name)));
                    //设置toolbar的图片,根据name获取key的位置，在用key的位置获取key的值
                    return replaceFragment(screenShotable, position, name);
                }
                else
                {
                    CustomSuperCardToast.makeText(MainActivity.this, name + "已在当前页面", "确定").show();
                    return screenShotable;
                }
            }
        }
    }

    /**
     * 替换Fragment
     *
     * @param screenShotable 应该是退回到主界面
     * @param position       选中某个栏目按钮的位置指针
     * @param itemname       项目的名称,用于选中哪个Fragment
     * @return
     */
    private ScreenShotable replaceFragment(ScreenShotable screenShotable, int position, String itemname)
    {
        View view = findViewById(R.id.content_frame);

        int finalRadius_最终半径 = Math.max(view.getWidth(), view.getHeight());//Math.max()比较大小,返回比较大的值
        // if (SystemData.systemData_系统版本号>= 21)
        //判断系统版本,如果大于等于5.0系统,使用圆形动画
        // 在5.0以下会崩溃,原因CircularReveal:1.0.4包在5.0才引入
        /**
         * 问题原因已知,首先，View view = findViewById(R.id.content_frame);必须放入RevealFrameLayout中，而不是直接引用RevealFrameLayout那个id
         * 其次，在ViewAnimationUtils的源码中，缺少import com.nineoldandroids.animation.ObjectAnimator;这个jar包
         * 引入 compile files('libs/nineoldandroids-2.4.0.jar')后问题解决
         */

        {
            SupportAnimator animator = ViewAnimationUtils.createCircularReveal(view, 0, position, 0, finalRadius_最终半径);
            animator.setInterpolator(new AccelerateInterpolator());
            animator.setDuration(ViewAnimator.CIRCULAR_REVEAL_ANIMATION_DURATION);
            findViewById(R.id.content_overlay).setBackgroundDrawable(new BitmapDrawable(getResources(), screenShotable.getBitmap()));
            animator.start();
        }

        ContentFragment contentFragment = ContentFragment.newFragment(itemname);

        getSupportFragmentManager().beginTransaction().replace(R.id.container_frame, contentFragment).commit();

        return contentFragment;
    }


    @Override
    public void disableHomeButton()
    {
        getSupportActionBar().setHomeButtonEnabled(false);

    }

    @Override
    public void enableHomeButton()
    {
        getSupportActionBar().setHomeButtonEnabled(true);
        drawerLayout.closeDrawers();

    }

    @Override
    public void addViewToContainer(View view)
    {
        linearLayout.addView(view);
    }

    /**
     * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
     * 消息通知
     */

    private void sendMessage()
    {
        VolleyHandler<String> stringVolleyHandler = new VolleyHandler<String>()
        {
            @Override
            public void reqSuccess(String response)
            {
                if (!response.endsWith("false"))
                {
                    Log.i("确认", "false");
                    final CustomDialog.Builder builder = new CustomDialog.Builder(MainActivity.this);
                    builder.setTitle("通知");
                    builder.setMessage(response);
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
                    {
                        @Override
                        public void onClick(DialogInterface dialog, int which)
                        {
                            builder.dismiss();
                        }
                    });
                    builder.show();
                }
            }

            @Override
            public void reqError(String error)
            {
                Log.i("确认", "error" + error);
            }
        };

        VolleyHttpRequest.String_request(MESSAGEURL + "phonenum=" + UserData.DATA_PHONENUM, stringVolleyHandler);
    }


    /**
     * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
     * 双击退出
     */
    /*private long exitTime = 0;

    public void ExitApp()
    {
        if ((System.currentTimeMillis() - exitTime) > 2000)
        {
            //Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();

            {//设置progress Toast
                SuperCardToast superCardToast =
                        new SuperCardToast(this, SuperToast.Type.PROGRESS_HORIZONTAL);
                superCardToast.setDuration(2000);
                superCardToast.setMaxProgress(200);
                superCardToast.setAnimations(SuperToast.Animations.POPUP);
                superCardToast.setText("再按一次退出程序");
                superCardToast.setSwipeToDismiss(true);
                new Handlerstart(superCardToast).handlerstart();//启动线程，传入superCardToast，进行对progress的赋值
                superCardToast.show();
            }
            exitTime = System.currentTimeMillis();
        }
        else
        {
            MARK_左侧栏已选中项 = "首页";
            MainActivity.this.finish();
        }
    }

    //superCardToast的progress的线程
    private class Handlerstart
    {
        private int i;
        private SuperCardToast superCardToast;
        private final int MSG = R.layout.activity_main;

        public Handlerstart(SuperCardToast superCardToast)
        {
            this.superCardToast = superCardToast;
        }

        public int handlerstart()
        {
            final Handler handler = new Handler()
            {
                @Override
                public void handleMessage(Message msg)
                {
                    super.handleMessage(msg);
                    switch (msg.what)
                    {
                        case MSG:
                            superCardToast.setProgress(i);
                    }
                }
            };

            new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    for (i = 0; i < 200; i++)
                    {
                        Message msg = new Message();
                        msg.what = MSG;
                        handler.sendMessage(msg);
                        try
                        {
                            Thread.sleep(10);
                        }
                        catch (InterruptedException e)
                        {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
            return 0;
        }

    }*/


    @Override
    public void onBackPressed()
    {
        ExitApp();
    }

    private void ExitApp()
    {
        MARK_左侧栏已选中项 = "首页";

        MainActivity_ExitDialog.showDialog(this);
    }


    /**
     * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
     * 双击退出
     */

    /*private class 初始化
    {
        private int MSG = R.layout.welcome;

        public 初始化()
        {
            Handler handler = new Handler()
            {
                @Override
                public void handleMessage(Message msg)
                {
                    super.handleMessage(msg);
                }
            };
            new Thread(new Runnable()
            {
                @Override
                public void run()
                {

                }
            }).start();
        }
    }*/

}

